package 模拟;

import java.util.Arrays;

/**
 * @PackageName: 模拟
 * @ClassName: LeetCode59 螺旋矩阵 II
 * @Author: chen jinxu
 * @Date: 2022/3/22 22:39
 * 给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
 */
public class LeetCode59 {
    public static void main(String[] args) {
        int[][] result = generateMatrix(3);
        for (int[] ints : result) {
            System.out.println(Arrays.toString(ints));
        }
    }

    public static int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int maxNum = n * n;
        // 定义上下左右4个方向
        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int startNum = 1;
        int row = 0;
        int col = 0;
        int index = 0;
        while (startNum <= maxNum) {
            matrix[row][col] = startNum;
            startNum++;
            int nextRow = row + directions[index][0];
            int nextCol = col + directions[index][1];
            if (nextRow >= n || nextCol >= n || nextRow < 0 || nextCol < 0 || matrix[nextRow][nextCol] != 0) {
                // 需要顺时针更换方向
                index = (index + 1) % 4;
            }
            row = row + directions[index][0];
            col = col + directions[index][1];
        }
        return matrix;
    }

}
